#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
激活码输入对话框
"""

import tkinter as tk
from tkinter import ttk, messagebox
import threading
from license_manager import LicenseManager

class LicenseDialog:
    """激活码输入对话框"""
    
    def __init__(self, parent, license_manager: LicenseManager):
        self.parent = parent
        self.license_manager = license_manager
        self.result = None
        
        # 创建对话框
        self.dialog = tk.Toplevel(parent)
        self.dialog.title("软件激活")
        self.dialog.geometry("500x400")
        self.dialog.resizable(False, False)
        self.dialog.transient(parent)
        self.dialog.grab_set()
        
        # 居中显示
        self.center_dialog()
        
        # 初始化界面
        self.init_ui()
        
        # 设置焦点
        self.license_entry.focus_set()
        
        # 绑定回车键
        self.dialog.bind('<Return>', lambda e: self.verify_license())
        self.dialog.bind('<Escape>', lambda e: self.cancel())
        
        # 模态对话框
        self.dialog.wait_window()
    
    def center_dialog(self):
        """居中显示对话框"""
        self.dialog.update_idletasks()
        x = (self.dialog.winfo_screenwidth() // 2) - (500 // 2)
        y = (self.dialog.winfo_screenheight() // 2) - (400 // 2)
        self.dialog.geometry(f"500x400+{x}+{y}")
    
    def init_ui(self):
        """初始化用户界面"""
        # 主框架
        main_frame = tk.Frame(self.dialog, bg='#f0f0f0')
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 标题
        title_frame = tk.Frame(main_frame, bg='#f0f0f0')
        title_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 图标和标题
        icon_label = tk.Label(title_frame, text="🔑", font=("Arial", 24), bg='#f0f0f0', fg='#2196F3')
        icon_label.pack(side=tk.LEFT, padx=(0, 10))
        
        title_label = tk.Label(title_frame, text="软件激活", 
                              font=("Arial", 18, "bold"), 
                              bg='#f0f0f0', fg='#333333')
        title_label.pack(side=tk.LEFT)
        
        # 说明文本
        desc_frame = tk.Frame(main_frame, bg='#f0f0f0')
        desc_frame.pack(fill=tk.X, pady=(0, 20))
        
        desc_text = """请输入您的激活码以使用软件功能。

激活码格式：XXXX-XXXX-XXXX-XXXX
激活码有效期：5分钟（测试用）

请确保：
1. 验证服务器已启动（http://localhost:3000）
2. 激活码在有效期内
3. 网络连接正常"""
        
        desc_label = tk.Label(desc_frame, text=desc_text, 
                             font=("Arial", 11), 
                             bg='#f0f0f0', fg='#666666',
                             justify=tk.LEFT, wraplength=450)
        desc_label.pack()
        
        # 激活码输入框架
        input_frame = tk.Frame(main_frame, bg='#f0f0f0')
        input_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 激活码标签
        license_label = tk.Label(input_frame, text="激活码:", 
                                font=("Arial", 12, "bold"), 
                                bg='#f0f0f0', fg='#333333')
        license_label.pack(anchor=tk.W, pady=(0, 5))
        
        # 激活码输入框
        self.license_entry = tk.Entry(input_frame, 
                                     font=("Arial", 14),
                                     width=30,
                                     relief=tk.SOLID,
                                     bd=1)
        self.license_entry.pack(fill=tk.X, pady=(0, 10))
        
        # 状态标签
        self.status_label = tk.Label(input_frame, text="", 
                                    font=("Arial", 10), 
                                    bg='#f0f0f0', fg='#666666')
        self.status_label.pack(anchor=tk.W)
        
        # 按钮框架
        button_frame = tk.Frame(main_frame, bg='#f0f0f0')
        button_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=(20, 0))
        
        # 测试连接按钮
        test_button = tk.Button(button_frame, 
                               text="🔍 测试连接", 
                               font=("Arial", 11),
                               bg='#FF9800', fg='white',
                               activebackground='#F57C00', activeforeground='white',
                               relief=tk.FLAT, bd=0,
                               cursor='hand2',
                               command=self.test_connection)
        test_button.pack(side=tk.LEFT)
        
        # 取消按钮
        cancel_button = tk.Button(button_frame, 
                                 text="取消", 
                                 font=("Arial", 12),
                                 bg='#f8f9fa', fg='#6c757d',
                                 activebackground='#e9ecef', activeforeground='#6c757d',
                                 relief=tk.FLAT, bd=1, highlightthickness=1,
                                 highlightbackground='#dee2e6',
                                 cursor='hand2',
                                 command=self.cancel)
        cancel_button.pack(side=tk.RIGHT)
        
        # 激活按钮
        self.activate_button = tk.Button(button_frame, 
                                        text="✅ 激活", 
                                        font=("Arial", 12, "bold"),
                                        bg='#4CAF50', fg='white',
                                        activebackground='#45a049', activeforeground='white',
                                        relief=tk.FLAT, bd=0,
                                        cursor='hand2',
                                        command=self.verify_license)
        self.activate_button.pack(side=tk.RIGHT, padx=(0, 10))
        
        # 进度条
        self.progress = ttk.Progressbar(main_frame, mode='indeterminate')
        self.progress.pack(fill=tk.X, pady=(10, 0))
        
        # 绑定输入框事件
        self.license_entry.bind('<KeyRelease>', self.on_license_input)
    
    def on_license_input(self, event=None):
        """激活码输入事件"""
        license_text = self.license_entry.get().strip()
        
        # 自动格式化激活码
        if len(license_text) > 0:
            # 移除所有非字母数字字符
            clean_text = ''.join(c for c in license_text if c.isalnum())
            
            # 格式化为 XXXX-XXXX-XXXX-XXXX
            if len(clean_text) <= 16:
                formatted = ''
                for i, char in enumerate(clean_text):
                    if i > 0 and i % 4 == 0:
                        formatted += '-'
                    formatted += char.upper()
                
                # 更新输入框（避免光标跳转）
                cursor_pos = self.license_entry.index(tk.INSERT)
                self.license_entry.delete(0, tk.END)
                self.license_entry.insert(0, formatted)
                
                # 恢复光标位置
                if cursor_pos <= len(formatted):
                    self.license_entry.icursor(cursor_pos)
        
        # 更新按钮状态
        self.update_button_state()
    
    def update_button_state(self):
        """更新按钮状态"""
        license_text = self.license_entry.get().strip()
        is_valid_format = len(license_text.replace('-', '')) == 16
        
        if is_valid_format:
            self.activate_button.config(state=tk.NORMAL, bg='#4CAF50')
        else:
            self.activate_button.config(state=tk.DISABLED, bg='#cccccc')
    
    def test_connection(self):
        """测试服务器连接"""
        self.status_label.config(text="正在测试连接...", fg='#FF9800')
        self.progress.start()
        
        def test_worker():
            try:
                is_connected, message = self.license_manager.test_server_connection()
                
                def update_ui():
                    self.progress.stop()
                    if is_connected:
                        self.status_label.config(text=f"✅ {message}", fg='#4CAF50')
                    else:
                        self.status_label.config(text=f"❌ {message}", fg='#f44336')
                
                self.dialog.after(0, update_ui)
                
            except Exception as e:
                def update_ui():
                    self.progress.stop()
                    self.status_label.config(text=f"❌ 连接测试失败: {str(e)}", fg='#f44336')
                
                self.dialog.after(0, update_ui)
        
        threading.Thread(target=test_worker, daemon=True).start()
    
    def verify_license(self):
        """验证激活码"""
        license_key = self.license_entry.get().strip()
        
        if not license_key:
            messagebox.showerror("错误", "请输入激活码")
            return
        
        # 验证格式
        clean_key = license_key.replace('-', '')
        if len(clean_key) != 16:
            messagebox.showerror("错误", "激活码格式不正确\n正确格式：XXXX-XXXX-XXXX-XXXX")
            return
        
        # 显示验证中状态
        self.activate_button.config(state=tk.DISABLED, text="验证中...")
        self.status_label.config(text="正在验证激活码...", fg='#FF9800')
        self.progress.start()
        
        def verify_worker():
            try:
                is_valid, message, license_data = self.license_manager.verify_license_online(license_key)
                
                def update_ui():
                    self.progress.stop()
                    self.activate_button.config(state=tk.NORMAL, text="✅ 激活")
                    
                    if is_valid:
                        self.status_label.config(text=f"✅ {message}", fg='#4CAF50')
                        self.result = license_data
                        messagebox.showinfo("激活成功", f"软件激活成功！\n\n激活码：{license_key}\n过期时间：{license_data.get('expire_date', '未知')}")
                        self.dialog.destroy()
                    else:
                        self.status_label.config(text=f"❌ {message}", fg='#f44336')
                        messagebox.showerror("激活失败", f"激活码验证失败：\n{message}")
                
                self.dialog.after(0, update_ui)
                
            except Exception as e:
                def update_ui():
                    self.progress.stop()
                    self.activate_button.config(state=tk.NORMAL, text="✅ 激活")
                    self.status_label.config(text=f"❌ 验证失败: {str(e)}", fg='#f44336')
                    messagebox.showerror("错误", f"验证过程中发生错误：\n{str(e)}")
                
                self.dialog.after(0, update_ui)
        
        threading.Thread(target=verify_worker, daemon=True).start()
    
    def cancel(self):
        """取消激活"""
        self.result = None
        self.dialog.destroy() 